# -*- coding: utf-8 -*-
# @Time        :2025/9/4 10:11
# @Author      :文刀水寿
# @File        : get_cookie.py
"""
 @Description :
"""
import json
import logging
from feishu import feishu_bitable
from FS_RPA import settings
from feishu.feishu_bitable import FeishuBiTable

logger = logging.getLogger(__name__)

class GetCookie:

    def __init__(self):
        self.table_id = 'tbl3OH1cSNH6U9zK'
        self.app_token = settings.APP_TOKEN
        self.current_index = 0
        self.records = []
        self.total = 0

    def _load_records(self):
        try:
            # 初始化飞书
            feishu_bitable = FeishuBiTable(
                app_config=settings.FEISHU_APP_CONFIGS,
                app_token=self.app_token
            )
            result = feishu_bitable.get_batch_records(table_id=self.table_id)
            self.records = result.get('data', {}).get('items', [])
            self.total = len(self.records)
            self.current_index = 0
        except Exception as e:
            print(f"加载记录失败: {str(e)}")
            self.records = []
            self.total = 0

    def get_next_cookie(self):
        """生成器：每次调用返回下一个cookie，循环获取"""
        if not self.records:
            self._load_records()

        while True:
            if self.total == 0:
                yield None
            else:
                current_record = self.records[self.current_index]
                cookie = ''.join([item['text'].strip() for item in current_record['fields']['cookie']])
                cookie_dict = json.loads(cookie)
                yield cookie_dict

                self.current_index = (self.current_index + 1) % self.total


if __name__ == "__main__":
    cookie_gen = GetCookie()
    generator = cookie_gen.get_next_cookie()
    cookies = next(generator)
    print(cookies)
    print(type(cookies))

